package com.iqiju.guagua.redtone.video.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class IDService {

    @Value("${http-url.id-gen-url}")
    private String idGenUrl;

    @Autowired
    private RestTemplate restTemplate;

    /** 获取全局唯一id */
    public long id(){
        Long id = null;
        JSONObject idObject = null;
        try {
            idObject = restTemplate.getForObject(idGenUrl, JSONObject.class);
            String state = idObject.getString("state");
            if ("0".equals(state)){
                id = idObject.getLong("content");
                log.info("发号器返回结果：{}", id);
            }
        } catch (Throwable e) {
            log.error("远程获取id异常");
            log.error(e.getMessage(), e);
            id = IdWorker.getId();
        }
        if (id == null){
            log.error("发号器返回错误！{}", idObject.toJSONString());
            return IdWorker.getId();
        }
        return id;
    }

}
